package com.passer.toolbox.common.core.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CmdUtils {
    /**
     * 运行终端命令
     *
     * @param cmd 终端命令
     * @return String 命令执行后打印值
     */
    public static String runCmd(String cmd) throws IOException {
        return runCmd(cmd, getCmdCharset());
    }

    /**
     * 运行终端命令
     *
     * @param cmd 终端命令
     * @param charset 终端编码
     * @return String 命令执行后打印值
     */
    public static String runCmd(String cmd, Charset charset) throws IOException {
        String command = "cmd /C " + cmd;
        Process process = Runtime.getRuntime().exec(command);
        String result;
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
        StringBuilder sb = new StringBuilder();
        while (((result = reader.readLine()) != null)) {
            sb.append(result).append("\n");
        }
        try {
            reader.close();
        } catch (IOException e) {
            log.warn("关闭输入流失败", e);
        }
        return sb.toString();
    }

    /**
     * 获取Windows控制台使用使用的编码
     *
     * @return 编码
     */
    public static Charset getCmdCharset() throws IOException {
        Charset charset = Charset.forName("GB2312");
        Optional<String> chcp = chcp();
        if (chcp.isPresent()) {
            switch (chcp.get()) {
                case "936":
                    charset = Charset.forName("GB2312");
                    break;
                case "65001":
                    charset = StandardCharsets.UTF_8;
                    break;
                default:

            }
        }
        return charset;
    }

    public static Optional<String> chcp() throws IOException {
        String
            runResult = CmdUtils.runCmd("chcp", StandardCharsets.UTF_8);
        Pattern pattern = Pattern.compile(".*?(\\d+)");
        Matcher matcher = pattern.matcher(runResult);
        if (matcher.find()) {
            return Optional.ofNullable(matcher.group(1));
        }
        return Optional.empty();
    }

    public static boolean ping(String url) throws IOException {
        return CmdUtils.runCmd("ping " + url).contains("TTL");
    }

}
